import {App} from "vue";
import {createPinia, defineStore} from 'pinia'
import XEUtils from "xe-utils";
import router from "@/router";
import {getSession, setSession} from "@/util/localCache";
// 1.定义并导出容器
//参数1：容器的id必须唯一 将来pinia会把所有的容器挂载到根容器
export const useStore = defineStore('mains', {
    // 类似于组件的data
    //1.必须是函数：这样是为了在服务渲染的时候避免交叉请求导致的数据状态污染
    //2.必须是箭头函数：这是为了更好的ts指引
    state: () => {
        return {
            login: [] as any,
            tabArr: ['David'] as any[],
            tabValue: 'David'
        }
    },
    //类似于组件的Component，用来封装计算属性 有缓存的功能
    getters: {
        // doubleCount: (state) => state.aaa * 2,
        // aaa10(state) {
        //     console.log('aaa10调用')
        //     return state.aaa + 50
        // },
        // bbb(){
        //     return this.doubleCount
        // }
    },
    // 封装业务逻辑修改state
    actions: {
        ChangeState(num: string, value: any) {
            switch (num) {
                case 'tabArr':
                    this.tabArr = value ? value : this.tabArr
                    break
                case 'login':
                    this.login = value ? value : this.login
                    break
                case 'tabValue':
                    this.tabValue = value ? value : this.tabValue
                    break
            }
        },
        pushTagData(val: string) {
            const joinIn = XEUtils.findIndexOf(this.tabArr, item => item === val) === -1
            if (joinIn) {
                this.tabArr.push(val)
                setSession('tabArr', this.tabArr)
            }
            router.replace('/home/' + val).then()
            this.tabValue = val
            setSession('tabValue', val)
        },
        clickTagData(val: any) {
            router.replace('/home/' + val).then()
            this.tabValue = val
            setSession('tabValue', val)
        },
        deleteTagData(name: any) {
            XEUtils.remove(this.tabArr, (item: any) => item === name)
            this.tabValue = this.tabArr[this.tabArr.length-1]
            setSession('tabArr', this.tabArr)
            setSession('tabValue', this.tabValue)
            router.replace('/home/' + this.tabValue).then()
        }
    }
})

export function setPinia(app: App<Element>): void {
    const pinia = createPinia()
    app.use(pinia)
}